package com.cph.common.http;

import com.alibaba.fastjson.JSON;
import com.cph.common.http.BeanMapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuqa
 * @projectName vehicle-files-management
 * @description: TODO
 * @date 2019/9/2 15:04
 */
@Service("httpUtilService")
public class HttpUtilService
{
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;

    /**
     * retry get方法
     *
     * @param headers  请求头需要设置的参数
     * @param dataBody 发送的数据
     * @param url      请求地址
     * @return HttpResponseResult 本次请求的状态
     * @throws
     * @author zhuqa
     * @method retryHttpGet
     */
    public HttpResponseResult httpGet(Map<String, Object> headers, Map<String, Object> dataBody, String url)
    {
        UriComponentsBuilder builder = orgUriComponentsBuilder(dataBody, url);
        logger.info("url   :" + url);
        HttpEntity<?> entity = new HttpEntity<>(orgHeader(headers));
        ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(),
                HttpMethod.GET,
                entity,
                String.class);
        return HttpResponseResult.success(response.getStatusCode().getReasonPhrase(),response.getBody());
    }

    /**
     * retry get方法
     *
     * @param variables 参数
     * @param url       请求地址
     * @return Map本次请求的状态
     * @throws
     * @author:zhuqa
     * @method retryHttpGet
     */
    public HttpResponseResult httpGet(Map<String, Object> variables, String url)
    {
        UriComponentsBuilder builder = orgUriComponentsBuilder(variables, url);
        HttpEntity<?> entity = new HttpEntity<>(orgHeader(null));
        ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(),
                HttpMethod.GET,
                entity,
                String.class);
        return HttpResponseResult.success(response.getStatusCode().getReasonPhrase(),response.getBody());
    }

    /**
     * retry get方法
     *
     * @param t   对象参数
     * @param url 请求地址
     * @return Map本次请求的状态
     * @throws
     * @author:willinggod
     * @method retryHttpGet
     */
    public HttpResponseResult httpGet(Object t, String url) throws IllegalAccessException,
            IntrospectionException,
            InvocationTargetException
    {
        Map<String, Object> variables = new HashMap<>();
        if (t != null)
        {
            variables = BeanMapUtils.BeanToMap(t);
        }
        return httpGet(variables, url);
    }


     public HttpResponseResult httpPost(Map<String, Object> dataBody, String url)
    {
        logger.info("dataBody value is ={}", JSON.toJSONString(dataBody));
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        HttpEntity<?> entity = new HttpEntity<>(dataBody);
        logger.info("entity value is ={}", JSON.toJSONString(entity));
        ResponseEntity<String> response = null;
        try
        {
            response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
            logger.info("response value is ={}",JSON.toJSONString(response));
        }
        catch (Exception e)
        {
            logger.error("Abnormal interface：" + e.getMessage());
        }
        return HttpResponseResult.success(response.getStatusCode().getReasonPhrase(),response.getBody());
    }

    /**
     * retry post方法
     *
     * @param headers  请求头需要设置的参数
     * @param dataBody 发送的数据
     * @param url      请求地址
     * @return HttpResponseResult 本次请求的状态
     * @throws
     * @author zhuqa
     * @method httpPost
     */
    public HttpResponseResult httpPost(Map<String, Object> headers, Map<String, Object> dataBody, String url)
    {

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        HttpEntity<?> entity = new HttpEntity<>(dataBody, orgHeader(headers));
        logger.info("httpPost entity value is={}",JSON.toJSONString(entity));
        ResponseEntity<String> response = null;
        try
        {
            response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
        }
        catch (Exception e)
        {
            logger.error("接口调用异常:" + e.getMessage());
        }
        return HttpResponseResult.success(response.getStatusCode().getReasonPhrase(),response.getBody());
    }

    /**
     * retry post方法
     *
     * @param headers 请求头需要设置的参数
     * @param object  发送的数据对象
     * @param url     请求地址
     * @return HttpResponseResult 本次请求的状态
     * @throws
     * @author zhuqa
     * @method retryHttpGet
     */
    public HttpResponseResult httpPost(Map<String, Object> headers, Object object, String url)
    {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        HttpEntity<?> entity = new HttpEntity<>(object, orgHeader(headers));
        ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(),
                HttpMethod.POST,
                entity,
                String.class,
                object);
        return HttpResponseResult.success(response.getStatusCode().getReasonPhrase(),response.getBody());
    }
//    public HttpResponseResult httpResponseInit(ResponseEntity<String> response)
//    {
//        if (response != null)
//        {
//            HttpResponseResult HttpResponseResult = new HttpResponseResult();
//            HttpResponseResult.setStatusCode(response.getStatusCodeValue());
//            HttpResponseResult.setStatusName(response.getStatusCode().getReasonPhrase());
//            HttpResponseResult.setHeader(response.getHeaders().toString());
//            if (response.getBody() != null)
//            {
//                if (response.hasBody())
//                {
//                    HttpResponseResult.setBody(response.getBody().toString());
//                }
//            }
//            return HttpResponseResult;
//        }
//        else
//        {
//            return null;
//        }
//    }
//
//    public String httpPost3(Map<String, String> map, String url)
//    {
//        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        CloseableHttpResponse response = null;
//        String resultString = "";
//        try
//        {
//            // 创建Http Post请求
//            HttpPost httpPost = new HttpPost(url);
//            List<NameValuePair> paramList = new ArrayList<>();
//            for (String key : map.keySet())
//            {
//                paramList.add(new BasicNameValuePair(key, map.get(key)));
//            }
//            // 模拟表单
//            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
//            httpPost.setEntity(entity);
///*            //根据需要，设置目前系统的标识
//            //设置请求头
//            httpPost.setHeader("System-Name", Constant.SYSTEM_UWS);
//            //设置本机ip地址
//            httpPost.setHeader("System-IP", IPUtils.getServerIp());*/
//            // 执行http请求
//            response = httpClient.execute(httpPost);
//            logger.info("response:" + response.toString());
//            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
//        }
//        catch (Exception e)
//        {
//            logger.error("post请求异常", e);
//        }
//        finally
//        {
//            try
//            {
//                response.close();
//            }
//            catch (IOException e)
//            {
//                logger.error("post请求异常", e);
//            }
//        }
//        return resultString;
//
//    }

    /**
     * 设置系统ip和系统标识名称
     *
     * @param headerVariables 请求头
     * @return HttpResponseResult
     * @throws
     * @author zhuqa
     */
    public HttpHeaders orgHeader(Map<String, Object> headerVariables)
    {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (null != headerVariables && !headerVariables.isEmpty())
        {
            for (Map.Entry<String, Object> headerEntry : headerVariables.entrySet())
            {
                if (StringUtils.isNotBlank(headerEntry.getKey()))
                {
                    String key = headerEntry.getKey();
                    Object value = headerEntry.getValue();
                    if (null == value)
                    {
                        value = "";
                    }
                    httpHeaders.set(key, value.toString());
                }
            }
        }
        if (httpHeaders.get("Accept") == null || StringUtils.isBlank(httpHeaders.get("Accept") + ""))
        {
            httpHeaders.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
        }
/*        //根据需要，设置目前系统的标识
        httpHeaders.set("System-Name", Constant.SYSTEM_UWS);
        //设置本机ip地址
        httpHeaders.set("System-IP", IPUtils.getServerIp());*/
        return httpHeaders;
    }

    /**
     * 设置请求url
     *
     * @param variables 请求附加参数
     * @param url       请求地址
     * @return HttpResponseResult
     * @throws
     * @author zhuqa
     */
    public UriComponentsBuilder orgUriComponentsBuilder(Map<String, Object> variables, String url)
    {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        for (Map.Entry<String, Object> entry : variables.entrySet())
        {
            if (StringUtils.isNotBlank(entry.getKey()))
            {
                String key = entry.getKey();
                Object value = entry.getValue();
                builder.queryParam(key, value);
            }
        }
        return builder;
    }
    public HttpResponseResult httpPostError(Map<String, Object> headers, Map<String, Object> dataBody, String url)
    {

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        HttpEntity<?> entity = new HttpEntity<>(dataBody, orgHeader(headers));
        logger.info("httpPost entity value is={}",JSON.toJSONString(entity));
        HttpResponseResult response = new HttpResponseResult();
        try {
            ResponseEntity<String> responseEntity =   restTemplate.exchange(builder.toUriString(),
                    HttpMethod.POST,
                    entity,
                    String.class,
                    dataBody);
            logger.info("ResponseEntity value is={}",JSON.toJSONString(responseEntity));
            return HttpResponseResult.success(responseEntity.getStatusCode().getReasonPhrase(),responseEntity.getBody());
        } catch (HttpStatusCodeException e) {
            if("401".equals(e.getStatusCode().toString())){
                logger.info("e ={}",JSON.toJSONString(e));
            }

        }
        return response;
    }
}
